<template>
  <div ref="vantaRef" style="width: 100%;height: 100vh"></div>
  <div class="back">
    <div class="right">
      <!-- 登录表单 -->
      <el-card style="width: 450px;height: 400px;display: flex;justify-content: center;align-items: center;background-color: rgba(255,255,255,0.9)">
        <el-input type="text" placeholder="手机号" v-model="loginUser.phone" />
        <el-input type="password" placeholder="密码（6~18位，包含数字和字母）" v-model="loginUser.password"/>
        <div style="display:flex;align-items: center;justify-content: center;margin-bottom: 20px;">
          <el-radio-group v-model="radio">
            <el-radio value="1" size="small">我要找工作</el-radio>
            <el-radio value="2" size="small">我要招人</el-radio>
          </el-radio-group>
        </div>
        <el-button type="primary" @click="toLogin">登录</el-button>
        <el-button link style="margin-left: 0;" type="primary" @click="toRegister">立即注册</el-button>
      </el-card>
    </div>
  </div>
  <el-dialog v-model="dialogVisible" style="width: 500px;">
    <el-steps style="max-width: 500px;" :active="active" align-center>
      <el-step title="第一步" description="输入注册信息" />
      <el-step title="完成" description="注册结果" />
    </el-steps>
    <div v-if="divVisible1" style="margin-top: 20px;">
      <el-select v-model="registerUser.status" placeholder="请选择你的身份" style="margin-bottom: 20px">
        <el-option label="求职者" value="0"></el-option>
        <el-option label="招聘者" value="1"></el-option>
      </el-select>
      <el-input v-model="registerUser.phone" placeholder="手机号"></el-input>
      <el-input v-model="registerUser.password" placeholder="请输入6~18位密码，同时包含数字和字母" type="password" show-password></el-input>
      <el-input v-model="registerUser.password1" placeholder="确认密码" type="password" show-password></el-input>
    </div>
    <div v-if="divVisible2">
      <el-result v-if="resultTrue" icon="success" title="注册成功！"></el-result>
      <el-result v-else icon="error" title="注册失败，该账号已存在！"></el-result>
    </div>
    <el-button style="margin-top: 12px" @click="next" type="primary">{{ dialogButton }}</el-button>
  </el-dialog>
</template>

<script setup lang="ts">
import {onBeforeMount, onMounted, ref} from "vue";
import {Action, ElMessage, ElMessageBox} from "element-plus";
import {useRouter} from "vue-router";
import {recruiterApi, seekerApi} from "../../api/app.js";
import {debounce} from "../../router/debounce";
import GLOBE from "vanta/src/vanta.globe"
import * as THREE from "three";

const vantaRef = ref(null);
let vantaEffect = null;
onMounted(() => {
  vantaEffect = GLOBE({
    el: vantaRef.value,
    THREE: THREE,
    mouseControls: true,
    touchControls: true,
    gyroControls: false,
    minHeight: 200.00,
    minWidth: 200.00,
    scale: 1.00,
    scaleMobile: 1.00,
    color: 0x3fa6ff,
    size: 1.5,
    backgroundColor: 0xeaeaea
  })
})
onBeforeMount(() => {
  if(vantaEffect) {
    vantaEffect.destroy();
  }
})

const reg_phone = /^1\d{10}$/; // 手机号正则（1开头11位）
const reg_password = /^(?=.*\d)(?=.*[A-z])[\da-zA-Z]{6,18}$/; // 密码正则（包含数字和字母 6~18位）

// 登录信息
const loginUser = ref({
  phone: '', // 手机号
  password: '', // 密码
})
const radio = ref('1'); // 身份
const router = useRouter();
// 登录操作
const toLogin = () => {
    loginFunc()
}

const loginFunc = debounce(
    function (){
  // 用户名或密码为空
  if(loginUser.value.phone == '' || loginUser.value.password == '') {
    ElMessageBox.alert('用户名或密码不得为空！', '操作失败', {
      confirmButtonText: '确认',
      callback: (action: Action) => {
        ElMessage({
          type: 'error',
          message: `操作失败`,
        })
      }
    });
  } else if(!reg_phone.test(loginUser.value.phone)) { // 账号格式错误
    ElMessageBox.alert('账号格式错误！', '操作失败', {
      confirmButtonText: '确认',
      callback: (action: Action) => {
        ElMessage({
          type: 'error',
          message: `操作失败`,
        })
      }
    });
  } else if(!reg_password.test(loginUser.value.password)) { // 密码格式错误
    ElMessageBox.alert('密码格式错误！', '操作失败', {
      confirmButtonText: '确认',
      callback: (action: Action) => {
        ElMessage({
          type: 'error',
          message: `操作失败`,
        })
      }
    });
  } else {
    if(radio.value == '1') { // 求职者
      seekerApi.login({
        phone: loginUser.value.phone,
        password: loginUser.value.password
      }).then(response => {
        console.log("登录信息",response)
        if(response.message == '数据不存在') {
          ElMessageBox.alert('该账号不存在！', '操作失败', {
            confirmButtonText: '确认',
            callback: (action: Action) => {
              ElMessage({
                type: 'error',
                message: `操作失败`,
              })
            }
          });
        } else if(response.message == '操作成功') {
          ElMessage({
            message: '登陆成功！',
            type: 'success',
          });
          // 存为全局变量
          localStorage.setItem(
              'seeker',
              JSON.stringify(response.data)
          )
          router.push('/seekerMain');
        } else if(response.message == '密码错误') {
          ElMessageBox.alert('密码错误', '操作失败', {
            confirmButtonText: '确认',
            callback: (action: Action) => {
              ElMessage({
                type: 'error',
                message: `操作失败`,
              })
            },
          });
        }
      }).catch(error => {
        console.log(error);
      })
    } else if(radio.value == '2') { // 招聘者
      recruiterApi.login({
        phone: loginUser.value.phone,
        password: loginUser.value.password
      }).then(response => {
        console.log("登录信息",response);
        if(response.message == '数据不存在') {
          ElMessageBox.alert('该账号不存在！', '操作失败', {
            confirmButtonText: '确认',
            callback: (action: Action) => {
              ElMessage({
                type: 'error',
                message: `操作失败`,
              })
            }
          });
        } else if(response.message == '操作成功') {
          ElMessage({
            message: '登陆成功！',
            type: 'success',
          });
          // 存为全局变量
          localStorage.setItem(
              'recruiter',
              JSON.stringify(response.data)
          );
          router.push('/recruiterMain');
        } else if(response.message == '密码错误') {
          ElMessageBox.alert('密码错误', '操作失败', {
            confirmButtonText: '确认',
            callback: (action: Action) => {
              ElMessage({
                type: 'error',
                message: `操作失败`,
              })
            },
          });
        }
      }).catch(error => {
        console.log(error);
      })
    }
  }
},500)

// 注册信息
const registerUser = ref({
  phone: '', // 手机号
  password: '', // 密码
  password1: '', // 确认密码
  status: "0", // 身份
})
const dialogVisible = ref(false); // 表单是否可视
const divVisible1 = ref(false); // 步骤1（输入注册信息）是否可视
const divVisible2 = ref(false); // 步骤2（注册结果）是否可视
const resultTrue = ref(true); // 注册结果 True成功 False失败
const active = ref(0); // 默认步骤从第一个开始
const dialogButton = ref('下一步'); // 表单按钮
// 注册操作
const toRegister = () => {
  dialogVisible.value = true;
  divVisible1.value = true;
  divVisible2.value = false;
}
// 下一步操作
const next = () => {
  if(active.value == 0) { // 当前为第一步，跳转到第二步
    // 有为空的地方
    if(registerUser.value.password === '' || registerUser.value.password1 === '' || registerUser.value.phone === '') {
      ElMessageBox.alert('输入不得为空', '操作失败', {
        confirmButtonText: '确认',
        callback: (action: Action) => {
          ElMessage({
            type: 'error',
            message: `操作失败`,
          })
        },
      })
    } else if(!reg_phone.test(registerUser.value.phone)) { // 手机号不满足格式
      ElMessageBox.alert('手机号输入不符合要求', '操作失败', {
        confirmButtonText: '确认',
        callback: (action: Action) => {
          ElMessage({
            type: 'error',
            message: `操作失败`,
          })
        },
      })
    } else if(!reg_password.test(registerUser.value.password)) { // 密码不满足格式
      ElMessageBox.alert('密码输入不符合要求', '操作失败', {
        confirmButtonText: '确认',
        callback: (action: Action) => {
          ElMessage({
            type: 'error',
            message: `操作失败`,
          })
        },
      })
    } else if(registerUser.value.password !== registerUser.value.password1) { // 两次密码输入不一致
      ElMessageBox.alert('两次密码输入不一致', '操作失败', {
        confirmButtonText: '确认',
        callback: (action: Action) => {
          ElMessage({
            type: 'error',
            message: `操作失败`,
          })
        },
      })
    } else { // 输入全合法
      // 如果是求职者
      if(registerUser.value.status == "0") {
        seekerApi.register({
          phone: registerUser.value.phone,
          password: registerUser.value.password
        }).then(response => {
          console.log(response);
          if(response.message == '操作成功') { // 注册成功
            resultTrue.value = true;
          } else if(response.message == '数据已经存在') {
            resultTrue.value = false;
          }
          divVisible1.value = false;
          divVisible2.value = true;
          dialogButton.value = '完成';
          active.value ++;
        }).catch(error => {
          console.log(error);
        })
      } else { // 如果是招聘者
        recruiterApi.register({
          phone: registerUser.value.phone,
          password: registerUser.value.password
        }).then(response => {
          if(response.message == '操作成功') { // 注册成功
            resultTrue.value = true;
          } else if(response.message == '数据已经存在') { // 已注册过
            resultTrue.value = false;
          }
          divVisible1.value = false;
          divVisible2.value = true;
          dialogButton.value = '完成';
          active.value ++;
        }).catch(error => {
          console.error(error);
        })
      }
    }
  } else if(active.value == 1) { // 当前为第二步，关闭弹窗
    dialogVisible.value = false;
    divVisible2.value = false;
    dialogButton.value = '下一步';
    active.value = 0;
    // 重置数据
    registerUser.value.phone = '';
    registerUser.value.password = '';
    registerUser.value.password1 = '';
  }
}
</script>

<style scoped>
.back {
  /*background-image: url("../../assets/images/E-1276020-643A361E.jpg");*/
  /*background-size: cover;*/
  /*background-repeat: no-repeat;*/
  width: 100%;
  height: calc(100vh);
  display: flex;
  justify-content: flex-end;
  align-items: center;
  position: absolute;
  top: 0
}
.right {
  position: absolute;
  left: 2%;
  width: 50%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0.8;
}
.el-input {
  margin-bottom: 20px;
}
.el-button {
  width: 100%;
}
</style>
